<?php

namespace api\modules\v1\controllers;

use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\UploadHelper;
use common\models\ding\Talk;
use Yii;

include(__DIR__ . '/../../../../vendor/ding/TopSdk.php');
include(__DIR__ . '/../../../../vendor/ding/dingtalk/DingTalkClient.php');
date_default_timezone_set('Asia/Shanghai');

/**
 * 默认控制器
 *
 * Class DefaultController
 * @package api\modules\v1\controllers
 * @property \yii\db\ActiveRecord $modelClass
 * @author jianyan74 <751393839@qq.com>
 */
class DingController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index','search','weekly','work','user'];

    /**
     * 批量进行日报数据添加
     */
    public function actionWeekly()
    {
        $cursor = 0;
        $count = [];
        while (1){
            $data = $this->getJournal($cursor)->result;
            if(!$data->data_list){
                break;
            }
            $arr = [];//定义数组
            foreach ($data->data_list as $v){
                $arr[] = [
                    'week'=>$v->contents[0]->value,'work'=>$v->contents[1]->value,'summary'=>$v->contents[2]->value,
                    'help'=>$v->contents[3]->value,'created_at'=>$v->create_time/1000,'creator_id'=>$v->creator_id,
                    'creator_name'=>$v->creator_name,'dept_name'=>$v->dept_name,'images'=>implode(',',$v->images),
                    'modified_time'=>$v->modified_time/1000,'remark'=>$v->remark,'report_id'=>$v->report_id,
                    'template_name'=>$v->template_name
                ];//整合添加数据
            }
            $count[] = Yii::$app->db->createCommand()
                ->batchInsert(Talk::tableName(),['week','work','summary','help','created_at','creator_id','creator_name','dept_name'
                    ,'images','modified_time','remark','report_id','template_name'],$arr)
                ->execute();//进行批量插入数据
            $cursor = $data->next_cursor;
        }
        $res = array_sum($count);
        return "success count:{$res}";
    }

    /**
     * 获取日志数据
     */
    public function getJournal($cursor)
    {
        $time = time()*1000;
        $endtime =strtotime('-5 days')*1000;
        $access_token = $this->getToken();
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiReportListRequest;
        $req->setStartTime("$endtime");
        $req->setEndTime("$time");
        $req->setSize("20");
        $req->setCursor($cursor);
        return $c->execute($req, $access_token, "https://oapi.dingtalk.com/topapi/report/list");
    }
    /**
     * 获取考勤打卡详情
     */
    public function getCheck($ids){
        $time = date('Y-m-d H:i:s');
        $endtime = date('Y-m-d H:i:s',time()-10800);
        $access_token = $this->getToken();
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiAttendanceListRecordRequest;
        $req->setUserIds($ids);
        $req->setCheckDateFrom($endtime);
        $req->setCheckDateTo($time);
        return $c->execute($req, $access_token, "https://oapi.dingtalk.com/attendance/listRecord");
    }

    /**
     * 批量进行打卡数据添加
     */
    public function actionWork()
    {
        $count = [];
        $ids= $this->getIds();
        $i = 1;
        while ($i<=ceil(count($ids)/50)){
            $data = $this->getCheck(array_slice($ids,($i-1)*50,50));
            $arr = [];//定义数组
            foreach ($data->recordresult as $v){
//                dd($v);die;
                $arr[] = [
                    'timeresult'=>$v->timeResult,'checktype'=>$v->checkType,'locationresult'=>$v->locationResult,
                    'sourcetype'=>$v->sourceType,'userId'=>$v->userId,'workdate'=>$v->workDate/1000,'userCheckTime'=>$v->userCheckTime/1000
                ];//整合添加数据
            }
            $count[] = Yii::$app->db->createCommand()
                ->batchInsert('rf_check',['timeresult','checktype','locationresult','sourcetype','userId'
                    ,'workdate','userCheckTime'],$arr)
                ->execute();//进行批量插入数据
            $i++;
        }
        $res = array_sum($count);
        return "success count:{$res}";
    }
    public function getToken(){
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiGettokenRequest;
        $req->setAppkey("dinghliy5osaxix0zxuy");
        $req->setAppsecret("ufMZ4cx8ethmlWZ95ZEiwivr-EA1gzCfp5hio-9bOfN0Ch6_JYWjT9uqBGapAYxO");
        $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/gettoken");
        return $resp->access_token;
    }

    /**
     * 获取员工id
     */
    public function getIds(){
        $access_token = $this->getToken();
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiUserGetDeptMemberRequest;
        $req->setDeptId("1");
        $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/user/getDeptMember");
        //return array_slice($resp->userIds,0,50);
        return $resp->userIds;
    }
    /**
     * 获取钉钉用户数据
     */
    public function getUser($ids)
    {
        $access_token = $this->getToken();
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
        $req = new \OapiSmartworkHrmEmployeeListRequest;
        $req->setUseridList($ids);
        return $c->execute($req, $access_token, "https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list");
    }
    /**
     * 批量进行钉钉用户添加
     */
    public function actionUser()
    {
        $count = [];
        $ids= $this->getIds();
        $i = 1;
        while ($i<=ceil(count($ids)/50)){
            $data = $this->getUser(implode(',',array_slice($ids,($i-1)*50,50)));
            $arr = [];//定义数组
            foreach ($data->result as $v){
                $arr[] = [
                    'name'=>$v->field_list[0]->value,'name_id'=>$v->userid
                ];//整合添加数据
            }
            $count[] = Yii::$app->db->createCommand()
                ->batchInsert('rf_name',['name','name_id'],$arr)
                ->execute();//进行批量插入数据
            $i++;
        }
        $res = array_sum($count);
        return "success count:{$res}";
    }
    public function actionIndex()
    {
        $firstday = strtotime(date('Y-m-d', time()-432000));
        return $firstday;
    }
}
